<template>
  <div>
    <div class="table-responsive">
      <table class="table table-hover">
        <caption></caption>
        <thead>
          <tr>
            <th></th>
            <th>商品名称</th>
            <th>单价</th>
            <th>数量</th>
            <th>金额</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in carList" :key="item.id">
            <td>
              <img style="width: 60px" :src="item.imgUrl" alt="" />
            </td>
            <td>
              <router-link :to="'/detail/' + item.id">
                {{ item.title }}
              </router-link>
            </td>
            <td>￥ {{ item.price }}</td>
            <td>
              <button
                class=" btn btn-outline-danger btn-sm"
                :disabled="item.quantity == 1"
                @click="subQuantity(item.id)"
              >
                –
              </button>
              &nbsp;{{ item.quantity }}&nbsp;
              <button
                class="btn btn-outline-danger btn-sm"
                @click="addQuantity(item.id)"
              >
                +
              </button>
            </td>
            <td>￥{{ calCurrentTotal(item) }}</td>
            <td>
              <button class="btn btn-danger" @click="deleteCar(item.id)">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="d-flex justify-content-between align-items-center">
      <strong>总价 {{ calAllTotal }}</strong>
      <router-link to="/check"
        ><button class="btn btn-danger">结算</button></router-link
      >
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  computed: {
    ...mapState(["carList"]),
    ...mapGetters(["calAllTotal"]),
  },
  data() {
    return {};
  },
  methods: {
    calCurrentTotal(item) {
      return parseFloat(item.price * item.quantity).toFixed(2);
    },
    subQuantity(id) {
      this.incrementQuantity(id);
    },
    addQuantity(id) {
      this.decrementQuantity(id);
    },
    deleteCar(id) {
      if (confirm("是否确定删除？")) {
        this.delCar(id);
      }
    },
    ...mapMutations([
      "alterQuantity",
      "incrementQuantity",
      "decrementQuantity",
      "delCar",
    ]),
  },
};
</script>
<style>
td {
  vertical-align: middle !important;
}
</style>
